<?php
namespace api\zhengmao\controller;
use api\zhengmao\model\CodeModel;
use api\zhengmao\model\UserModel;
use api\zhengmao\validate\UserValidate;
use cmf\controller\RestBaseController;
use think\Request;

class LoginController extends RestBaseController
{
//    public function login()
//    {
//        $data = input('post.');
//        $mobile = UserModel::where('mobile',$data['mobile'])->find();
//        if (!$mobile){
//            return error('该账户不存在');
//        }else{
//            return  success('登录成功', ['token' => sendToken($mobile['id'],$mobile['mobile'])]);
//        }
//    }
    public function login(Request $request)
    {
        $data=$request->param();
        $validate = new UserValidate();
        $result = $validate->scene('login')->check($data);

        if ($result !== true) {
            return error($validate->getError());
        }
        $sel = UserModel::where('mobile','=',$data['mobile'])->find();
        if(empty($sel)){
            return error('手机号错误');
        }
        $code = CodeModel::where('mobile',$data['mobile'])->find();
        if(time() - $code['send_time'] > 600)
        {
            CodeModel::where('mobile','=',$data['mobile'])->delete();
            return error('验证码已过期');
        }
        if($data['code'] == $code['code'])
        {
            $token = sendToken($sel['id'],$sel['mobile']);
            $this->success(
                '登录成功', ['data'=>$token]);
        }else{
            $this->error('登录失败');
        }

    }
    public function register()
    {
        $data =input('post.');
        $validate = new UserValidate();
        $result = $validate->scene('register')->check($data);
        if(!$result){
            echo $validate->getError();
        }
        $user = UserModel::where('mobile',$data['mobile'])->find();
        if($user){
            return error('该手机号已被注册');
        }
        $code = CodeModel::where('mobile',$data['mobile'])->find();
        if(time() - $code['send_time'] > 600)
        {
            CodeModel::where('mobile','=',$data['mobile'])->delete();
            return error('验证码已过期');
        }
        if($code['code'] != $data['code'])
        {
            return error('验证码错误');
        }
        //时间过期删除
        $data['create_time'] = time();
        if(UserModel::create($data)){
            $token = sendToken($user['id'],$user['mobile']);
            return success('注册成功',['data'=>$token]);
        }else{
            return error('注册失败');
        }
    }
    public  function yzm()
    {
        $data = input('post.');
        sendCode($data['mobile']);
    }
}
